from sqlalchemy.orm import sessionmaker
from api.models.api_models import UserInfo

class UserInfoDAO:
    def __init__(self, engine):
        self.engine = engine
        self.Session = sessionmaker(bind=self.engine, expire_on_commit=False)

    def create(self, user_id, user_name, password, identity):
        session = self.Session()
        user = UserInfo(user_id=user_id, user_name=user_name, password=password, identity=identity)
        session.add(user)
        session.commit()
        session.close()
        return user

    def read(self, user_id):
        session = self.Session()
        user = session.query(UserInfo).filter_by(user_id=user_id).first()
        session.close()
        return user

    def update(self, user_id, user_name=None, password=None, identity=None):
        session = self.Session()
        user = session.query(UserInfo).filter_by(user_id=user_id).first()
        if user_name is not None:
            user.user_name = user_name
        if password is not None:
            user.password = password
        if identity is not None:
            user.identity = identity
        session.commit()
        session.close()

    def delete(self, user_id):
        session = self.Session()
        user = session.query(UserInfo).filter_by(user_id=user_id).first()
        session.delete(user)
        session.commit()
        session.close()